const model = require('../models/BaseModel.js')
const { ORDER } = require('../config/tableConfig.js')
const { ORDERFIELD } = require('../fields/orderField.js')


//orderData,userInfo
const create = (orderData) => {
    let orderdetailS = []
    // 添加订单详情
    let order_id = new Date().getTime()
    for (let product of orderData.products) {
        let params_order_detail = {
            product_id: product._id,
            product_name: product.product_name,
            product_price: product.product_sell_price,
            product_count: product.counts,
        }
        orderdetailS.push(params_order_detail)
    }
    // 订单信息
    let params_order = {
        order_id: order_id,
        buyer_openid: orderData.address.buyer_openid,
        buyer_name: orderData.address.name,
        buyer_phone: orderData.address.telephone,
        buyer_address: orderData.address.area+orderData.address.detail,
        // order_amount: orderData.amount,
        order_status: orderData.status,// 默认未付款
        create_time: new Date().toLocaleString(),
        order_image:orderData.products[0].product_imgs[0],
        orderdetail: orderdetailS,
        total_price:orderData.totalPrice
    }

    // 订单生成
    let order = model.add(ORDER, params_order);
    return order
}
/**
 * 根据订单id获取订单信息
 * @param {*} orderId 
 */
const getOrderById = (orderId) => {
    return model.findById(ORDER, ORDERFIELD, orderId)
}

/**
 * 根据用户openid获取信息
 * @param {*} userInfo 
 */
const getOrderList = (openId, page = 0, size = 10, order = {}) => {
    order.name = 'create_time'
    order.orderBy = 'desc'
    let options = { buyer_openid: openId }
    return model.query(ORDER, ORDERFIELD, options, page, size, order)
}

const getOrders = (order = {}) => {
    order.name = 'create_time'
    order.orderBy = 'desc'
    return model.queryAll(ORDER, ORDERFIELD,order)
}

const delOrder = (orderId) => {
    return model.remove(ORDER,orderId)
}
const updateOrder = (orderId,order) => {
    return model.update(ORDER,order,orderId)
}
module.exports = {
    create,
    getOrderById,
    getOrderList,
    delOrder,
    updateOrder,
    getOrders,
  

}
